package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    /*用户登录成功后,spring security框架会在认证成功之后将用户信息保存到框架提供的应用上下文对象.
    在浏览器的session域中,所以在用户退出时,配置文件需要将session销毁掉*/
    @RequestMapping("/getUsername")
    //获取当前登录用户的用户名
    public Result getUsername() {
        //当spring security完成认证之后,会将当前用户信息保存到框架提供的上下文对象
        org.springframework.security.core.userdetails.User user
                = (org.springframework.security.core.userdetails.User)
                SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if (user != null) {
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
        } else {
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }
}
